package com.cskaoyan.aspectj;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.po.MarketAdmin;
import com.cskaoyan.bean.po.MarketLog;
import com.cskaoyan.bean.po.MarketOrder;
import com.cskaoyan.mapper.MarketLogMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Auther: Yang Yi-zhou
 * @Date: 2022/9/13 09:11
 * @Description:
 */
@Component
@Aspect
public class OperateLogAspectJ {
    @Autowired
    MarketLogMapper marketLogMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Pointcut("execution(* com.cskaoyan.controller..*(..)))")
    private void log() {
    }

    @Around("log()")
    public Object around(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        Object[] args = joinPoint.getArgs();
        if (requestURI.startsWith("/admin")) {
            MarketLog record = new MarketLog();
            Object proceed = null;
            Object info = null;
            try {
                Object attribute = SecurityUtils.getSubject().getSession().getAttribute("info");
                if (attribute != null) {
                    info = attribute;
                }
                proceed = joinPoint.proceed(args);
                return proceed;
            } catch (Throwable e) {
                record.setStatus(false);
                throw new RuntimeException(e);
            } finally {
                // 用户名
                Object attribute = SecurityUtils.getSubject().getSession().getAttribute("info");
                if (attribute != null) {
                    info = attribute;
                }
                if (info == null) {
                    record.setAdmin("游客");
                }
                if (info instanceof MarketAdmin) {
                    MarketAdmin admin = (MarketAdmin) info;
                    record.setAdmin(admin.getUsername());
                }
                // ip

                String ip = request.getRemoteAddr();
                record.setIp(ip);
                // type
                int type = 0;
                if (requestURI.startsWith("/admin/order")) {
                    type = 2;
                } else if (requestURI.startsWith("/admin/auth")) {
                    type = 1;
                }
                record.setType(type);
                // action
                record.setAction(joinPoint.getSignature().toShortString());
                // status
                if (record.getStatus() == null) {
                    record.setStatus(true);
                }
                // result
                if (proceed != null && proceed instanceof BaseRespVo) {
                    BaseRespVo proceed1 = (BaseRespVo) proceed;
                    String msg = proceed1.getErrmsg();
                    if (msg.length() > 100) {
                        msg = msg.substring(0, 100) + "...";
                    }
                    record.setResult(msg);
                }
                if (record.getResult() == null) {
                    record.setResult("成功");
                }
                // comment
                if (requestURI.startsWith("/admin/order/delete")) {
                    // 获取订单编号
                    Map map = (Map) args[0];
                    Integer orderId = (Integer) map.get("orderId");
                    // 根据id去查订单编号
                    MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
                    String comment = "删除订单：" + marketOrder.getOrderSn();
                    record.setComment(comment);
                }

                // add_time update_time
                record.setAddTime(new Date());
                record.setUpdateTime(new Date());

                marketLogMapper.insertSelective(record);
            }
        }
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
